package com.yssoft.controller.core;

import com.alibaba.fastjson.JSONObject;
import com.yssoft.entity.core.TAccounts;
import com.yssoft.entity.core.TManagementSystem;
import com.yssoft.service.core.ManagementSystemService;
import com.yssoft.shiro.MyRealm;
import com.yssoft.utils.SessionUtil;
import com.yssoft.utils.UploadFile;
import com.yssoft.utils.UserHelper;
import lombok.extern.flogger.Flogger;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * @author 于兴达
 * @time 2018/4/25 下午 04:30
 * @说明 管理制度控制器
 */
@Controller
@RequestMapping("/managementSystem")
public class ManagementSystemController {
    @Autowired
    private ManagementSystemService managementSystemService;
    private static Logger logger = Logger.getLogger(UploadFile.class);
    private static String WORKDIR;
    private static final String PROGRAM_NAME = "M_";

    @Value("${local_path}")
    public void setWorkdir(String workdir) {
        WORKDIR = workdir;
    }

    /**
     * 跳转到管理制度信息页面
     *
     * @return
     */
    @RequestMapping("/managementSystemPage")
    public String managementSystemPage() {

        return "core/managementSystem/managementSystemList";
    }

    /**
     * 获取管理制度数据
     *
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/findManagementSystemPage")
    @ResponseBody
    public JSONObject findPersonPage(@RequestParam(name = "page", defaultValue = "0") int page, @RequestParam(name = "limit", defaultValue = "10") int limit, String managementSystemName) {
        JSONObject jsonObject = managementSystemService.queryManagementSystemPage(page, limit, managementSystemName);
        return jsonObject;
    }

    /**
     * 跳转到添加管理制度页面
     *
     * @return
     */
    @RequestMapping("managementSystemEditPage")
    public String managementSystemEditPage(String systemId, Model model) {
        if (systemId != null && systemId.trim().length() > 0) {
            //修改
            Integer managementSystemId = Integer.parseInt(systemId);
            TManagementSystem managementSystem = managementSystemService.queryManagementSystemById(managementSystemId);

            model.addAttribute("managementSystem", managementSystem);
        }
        return "core/managementSystem/managementSystemEdit";
    }

    /**
     * 保存管理制度信息
     *
     * @param
     * @return
     */
    @RequestMapping("saveManagementSystem")
    public String saveManagementSystem(ServletRequest request) {

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String url = request.getParameter("url");
        String fileName = request.getParameter("fileName");
        String fileByte = request.getParameter("fileByte");
        if (id != null && !"".equals(id)) {
            //修改
            TManagementSystem managementSystem = managementSystemService.queryManagementSystemById(Integer.parseInt(id));
            managementSystem.setCreateTime(managementSystem.getCreateTime());
            managementSystem.setName(name);
            managementSystem.setUrl(url);
            managementSystem.setFileName(fileName);
            managementSystem.setFileByte(fileByte);
            managementSystemService.editManagementSystem(managementSystem);
        } else {
            TManagementSystem managementSystem = new TManagementSystem();
            //添加
            managementSystem.setDeleteFlag("0");
            managementSystem.setCreateTime(new Date());
            managementSystem.setName(name);
            managementSystem.setUrl(url);
            managementSystem.setFileName(fileName);
            managementSystem.setFileByte(fileByte);
            Session session = SecurityUtils.getSubject().getSession();
            TAccounts acc = (TAccounts) session.getAttribute(SessionUtil.USER_SESSION_KEY);
            managementSystem.setCreatorId(acc.gettPId());
            managementSystem.setT_e_id(acc.gettEId());
            MyRealm.ShiroUser user = UserHelper.getCurrentUser();
            managementSystem.setCreatorName(user.getName());
            managementSystem.setCreatorId(user.getId());
            managementSystemService.addManagementSystem(managementSystem);
        }
        return "redirect:managementSystemPage";
    }

    /**
     * 删除管理制度信息
     *
     * @param systemId
     * @return
     */
    @RequestMapping("/delManagementSystem")
    public String delManagementSystem(String systemId) {
        Integer managementSystemId = Integer.parseInt(systemId);
        int result = managementSystemService.delManagementSystem(managementSystemId);
        if (result > 0) {
            return "success";
        } else {
            return "error";
        }
    }

    /**
     * 多选删除管理制度信息
     *
     * @param systemIds
     * @return
     */
    @RequestMapping("/delManagementSystems")
    @ResponseBody
    public String delManagementSystems(String systemIds) {
        String[] personIdArray = systemIds.split(",");
        int result = 0;
        for (String s : personIdArray) {
            Integer managementSystemId = Integer.parseInt(s);
            result = managementSystemService.delManagementSystem(managementSystemId);
        }
        if (result > 0) {
            return "success";
        } else {
            return "error";
        }
    }

    /**
     * 附件上传
     *
     * @param file
     * @return
     * @author 王永宁
     */
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file) {
        String json = null;
        try {
            String fileNames = UploadFile.processUploadedFile(file);
            json = "{\"code\":\"0\",\"url\":\"" + fileNames + "\"}";
            return json;
        } catch (Exception e) {
            json = "{\"code\":\"1\"}";
            return json;
        }

    }

    @RequestMapping("/download/{fileName:.+}")
    public void downloadFile(@PathVariable String fileName, HttpServletResponse response) {
        try {
            // 设置文件保存路径
            String filePath = String.format("%s%s%s", WORKDIR, File.separatorChar, fileName);
            File file = new File(filePath);
            // 检查文件是否存在
            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("File not found");
                return;
            }

            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setContentLength((int) file.length());

            // 获取文件输入流和响应输出流
            try (InputStream inputStream = new FileInputStream(file);
                 OutputStream outputStream = response.getOutputStream()) {

                // 缓冲区大小
                byte[] buffer = new byte[4096];
                int bytesRead;

                // 读取文件并写入响应
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.flush();
            }
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                response.getWriter().write("File download failed");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
